#!/bin/sh
# Copyright (c) 2014, bkil.hu
# This program is free software and can be distributed under the terms of
# the GNU General Public License v2,
# see COPYING for detailed licensing terms.

# User info:
# Tool to record Hungarian national television for timeshifted
# viewing (e.g., mobile device without Internet connection)
# Currently only m2 is supported.
# Required: wget
#
# Developer info:
# TODO test in multiple countries for extended periods
# TODO more channels
# TODO automatic retry with progressively lower quality on connection failure
# TODO parameterize wget with log level

main() {
 [ $# -ge 3 -a $# -le 4 ] || {
  echo "usage: $0 <HHMM start time> <HHMM end time> <title> [<quality 1..5>]" >&2
  echo "e.g.: $0 2040 2120 jamie_30_perces_kajai 5" >&2
  exit 1
 }
 export LOGLEVEL=1 # 0=none, 1=light

 record "$@"
}

record() {
 [ $# -ge 3 -a $# -le 4 ] || exit 1
 local START="$1" # HHMM
 local END="$2" # HHMM
 local NAME="$3"
 local QUALITY="${4-3}" # 1=minimum .. 5=maximum
 local CH="m2"

 while [ `hhmm` -lt $START ]
 do
  sleep 30
 done

 local TMP="`fetch_pre_keys "$CH"`"
 local PRE="`echo "$TMP" | sed -n "1 p"`"
 local KEYS="`echo "$TMP" | sed -n "2 p"`"
 local CHUNKBASE="`fetch_chunkbase "$PRE" "$KEYS" "$QUALITY"`"
 `xlog '$PRE $KEYS $CHUNKBASE'`
 while [ `hhmm` -lt $END ]
 do
  {
   fetch_current_chunks "$PRE" "$KEYS" "$CHUNKBASE" |
   while read TSBASE
   do
    local FILE="`echo "$TSBASE" | sed -r "s~^.*_([0-9]*).ts$~\1.part.$NAME.ts~"`"
    if [ ! -f "$FILE" ]; then
     touch "$FILE" # TODO: hazard
     wget -nv -O "$FILE" "$PRE$TSBASE$KEYS"
    fi
   done
  } &
  sleep 9
 done

 combine "$NAME" "`date +%Y%m%dT$START-$CH-`$NAME.ts"
}

fetch_pre_keys() {
 [ $# -eq 1 ] || exit 1
 local CH="$1"
# http://www.mtv.hu
# http://www.mediaklikk.hu/m2
# http://www.mediaklikk.hu/media-lejatszo/?ch=2
# http://inside.gamaxmedia.hu/player-inside?userid=mtva&streamid=mtv2live&width=460&height=260
 case $CH in
  m2) local ID="mtv2" ;;
  *) exit 1
 esac
 wget -nv -O- "http://admin.gamaxmedia.hu/player-inside-full?streamid=${ID}live&userid=mtva&height=260&width=460" |
 grep " *{ 'file': " |
 sed -r "s~^ *\{ 'file': '([^']*/)[^'?]*([?][^'/]*)'.*$~\1\n\2~"
# http://cdn2.gamaxmedia.hu/streams/mtva/mtv2live.smil/playlist.m3u8?keys=SNRg1SGBY2kAN0JZ42ovuQ&keyt=1391129080
}

fetch_chunkbase() {
 [ $# -eq 3 ] || exit 1
 local PRE="$1"
 local KEYS="$2"
 local QUALITY="$3"
 wget -nv -O- "${PRE}playlist.m3u8$KEYS" |
 grep -v "^#" |
 sed -n "$QUALITY p"
}

fetch_current_chunks() {
 [ $# -eq 3 ] || exit 1
 local PRE="$1"
 local KEYS="$2"
 local CHUNKBASE="$3"
 wget -nv -O- "${PRE}$CHUNKBASE$KEYS" |
 grep -v "^#"
}

combine() {
 [ $# -eq 2 ] || exit 1
 local NAME="$1"
 local FILE="$2"
 `xlog '$FILE'`
 ls [0-9]*.part.*.ts |
 grep -E "^[0-9]+\.part\.${NAME}\.ts$" |
 sort -n |
 while read PART
 do
  cat "./$PART" >> "$FILE" || exit 1
  rm "./$PART"
 done
}

hhmm() {
 date "+%H%M"
}

log_lines() {
 [ $# -eq 0 ] || exit 1
 while read S
 do
  log "$S"
 done
}

xlog() {
# usage: `xlog '$VARIABLE'`
 printf "eval log '%s'\n" "$* = `eval echo $@`"
}

log() {
 [ $# -eq 1 ] || exit 1
 local S="$1"
 if [ -z "$LOGLEVEL" -o $LOGLEVEL -eq 0 ]; then
  :
 elif [ $LOGLEVEL -eq 1 ]; then
  printf "debug: %s %s\n" `date "+%Y%m%dT%H%M%S.%N"` "$S" >&2
 else
  exit 1
 fi
}

main "$@"

